package com.systop.asset.service.impl;

import com.systop.asset.entity.*;
import com.systop.asset.entity.Process;
import com.systop.asset.entity.vo.AssetAssignmentDetailVO;
import com.systop.asset.entity.vo.AssetAssignmentVO;
import com.systop.asset.entity.vo.ProcessVo;
import com.systop.asset.enums.HttpCodeEnum;
import com.systop.asset.exception.SystemException;
import com.systop.asset.mapper.*;
import com.systop.asset.service.IProcessService;
import com.systop.asset.service.IWorkFlowService;
import com.systop.asset.utils.QRCodeGenerator;
import com.systop.asset.utils.RandomCodeGenerator;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 审批列表Service业务层处理
 * 
 * @author mu
 * @date 2025-06-24
 */
@Service
public class ProcessServiceImpl implements IProcessService {
    @Resource
    private ProcessMapper processMapper;
    @Autowired
    private IWorkFlowService workFlowService;
    @Resource
    private ProcessRecordMapper recordMapper;
    @Resource
    private ProcessTemplateMapper templateMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AssetMapper assetMapper;
    @Autowired
    private AssetAssignmentsMapper assetAssignmentsMapper;
    /**
     * 查询审批列表
     * 
     * @param id 审批列表主键
     * @return 审批列表
     */
    @Override
    public Process selectProcessById(Long id)
    {
        return processMapper.selectProcessById(id);
    }

    /**
     * 查询审批列表列表
     * 
     * @param process 审批列表
     * @return 审批列表
     */
    @Override
    public List<Process> selectProcessList(Process process)
    {
        return processMapper.selectProcessList(process);
    }

    /**
     * 新增审批列表
     * 
     * @param process 审批列表
     * @return 结果
     */
    @Override
    public int insertProcess(Process process)
    {
        process.setCreateTime(new Date());
        return processMapper.insertProcess(process);
    }

    /**
     * 修改审批列表
     * 
     * @param process 审批列表
     * @return 结果
     */
    @Override
    public int updateProcess(Process process)
    {
        process.setUpdateTime(new Date());
        return processMapper.updateProcess(process);
    }

    /**
     * 批量删除审批列表
     * 
     * @param ids 需要删除的审批列表主键
     * @return 结果
     */
    @Override
    public int deleteProcessByIds(Long[] ids)
    {
        return processMapper.deleteProcessByIds(ids);
    }

    /**
     * 删除审批列表信息
     * 
     * @param id 审批列表主键
     * @return 结果
     */
    @Override
    public int deleteProcessById(Long id)
    {
        return processMapper.deleteProcessById(id);
    }

    /**
     * 发起申请：
     *   templateId：申请模板id:1 资产借用申请 2 耗材领用申请 3 资产保修申请 4 资产归还申请
     *   userId： 申请人id
     *   deptId：申请人部门id
     *   businessId：申请业务id
     * @param vo 审批参数
     */
    @Override
    @Transactional
    public void publishProcess(ProcessVo vo) {
        //向审核表中添加数据
        //查询申请用户信息
        User user = userMapper.selectUserById(vo.getUserId());
        //根据id查询模板信息
        ProcessTemplate template = new ProcessTemplate();
        if (vo.getTemplateId() == null) {
            template.setTemplateName(vo.getProcessType());
            template.setStatus(0); //状态0开启
            template = templateMapper.selectProcessTemplateList(template).get(0);
        }else {
            template = templateMapper.selectProcessTemplateById(vo.getTemplateId());
        }

        //创建审核对象
        Process process = new Process();
        process.setCode(RandomCodeGenerator.generateCustomCode("SP"));//资产审批
        process.setProcessTemplateId(vo.getTemplateId());//流程模板id
        process.setDeptId(vo.getDeptId());
        process.setStatus(1);//状态：审核中
        process.setCreateTime(new Date());//发起审核时间
        process.setProcessType(template.getTemplateName());
        process.setUserId(vo.getUserId()); //申请人id
        process.setTitle(user.getUsername()+"发起" + template.getTemplateName());
        process.setBusinessId(vo.getBusinessId());
        //process.setDescription(assetAssignments.getUsagePurpose()); //描述
        //新增审核信息
        processMapper.insertProcess(process);
        //发起申请
        ProcessRecord record =  workFlowService.publishProcess(process,template);
        //更新审核表中数据:在发起审核中修改了一些数据
        processMapper.updateProcess(process);

        if (record!=null){
            //向审核记录表中添加数据
            recordMapper.insertProcessRecord(record);
        }
    }

    /**
     * 流程审批
     * @param vo 审批数据
     */
    @Override
    @Transactional
    public void approveProcess(ProcessVo vo) {
        //根据流程id查询流程
        Process process = processMapper.selectProcessById(vo.getProcessId());
        //流程审批
        ProcessRecord record =  workFlowService.approveProcess(process,vo);
        //更新审核记录
        processMapper.updateProcess(process);
        //新增审批记录
        if (record!=null){
            //向审核记录表中添加数据
            recordMapper.insertProcessRecord(record);
        }

        //根据审批结果（2审批通过、2撤回、-1驳回），维护业务数据
        if (process.getStatus()==2 || process.getStatus()==3 || process.getStatus()==-1 ){
            if (process.getProcessType().contains("资产借用")){
                //维护资产借用
                maintainAssentBorrow(process);
            }
        }

    }


    /**
     * 根据审批结果，维护资产借用
     * @param process
     */
    private void maintainAssentBorrow(Process process) {
        //获取资产借用信息及其借用详情
        AssetAssignmentVO assetAssignmentVO = assetAssignmentsMapper.selectDetail(process.getBusinessId().toString());
        //资产借用记录
        AssetAssignments assetAssignments = assetAssignmentsMapper.selectAssetAssignmentsById(assetAssignmentVO.getId());
        //资产需要维护的数据
        Integer assetStatus = null;//资产状态
        Long locationId = null; //位置id
        Long deptId = null; //部门id
        Long assignedTo = null; //领用人id
        //审批通过
        if (process.getStatus() == 2){
            //资产表：将资产状态修改成2(使用中)、同时修改资产位置id、部门id
            assetStatus = 2;//资产状态
            locationId = assetAssignments.getLocationId();
            deptId = assetAssignments.getDeptId();
            assignedTo=assetAssignments.getOperatorId();
            //资产借用记录：使用状态为1（正常使用）
            assetAssignments.setUseStatus(1L);
        }
        //审批撤回
        if (process.getStatus() == 3){
            //资产表：将资产状态修改成0(闲置)、同时修改资产领用人id
            assetStatus = 0;//资产状态
            //资产借用记录：使用状态为5（撤回）
            assetAssignments.setUseStatus(5L);
        }
        //审批驳回
        if (process.getStatus() == -1){
            //资产表：将资产状态修改成0(闲置)、同时修改资产领用人id
            assetStatus = 0;//资产状态
            //资产借用记录：使用状态为6（驳回）
            assetAssignments.setUseStatus(6L);
        }
        //更新资产借用
        assetAssignmentsMapper.updateAssetAssignments(assetAssignments);
        //循环更新资产对象
        for (AssetAssignmentDetailVO detail : assetAssignmentVO.getAssets()){
            //创建资产对象
            Asset asset = new Asset();
            asset.setId(detail.getAssetsId());
            asset.setStatus(assetStatus);
            asset.setLocationId(locationId);
            asset.setDeptId(deptId);
            asset.setAssignedTo(assignedTo);
            assetMapper.updateAsset(asset);
        }

    }


    /**
     * 撤销审核
     * @param processId
     * @param userId
     */
    @Override
    @Transactional
    public void revokeProcess(Long processId, Long userId) {
        //查询流程
        Process process = processMapper.selectProcessById(processId);
        //判断用户id是否是同一个人
        if (process.getUserId() == userId ){
            //执行撤销操作
            ProcessRecord record = workFlowService.revokeProcess(process);
            //更新审核
            processMapper.updateProcess(process);
            //新增审核记录
            recordMapper.insertProcessRecord(record);

            //根据撤销审批结果，维护业务数据
            if (process.getProcessType().contains("资产借用")){
                //维护资产借用
                maintainAssentBorrow(process);
            }
        }else{
            throw new SystemException(HttpCodeEnum.REVOKE_PROCESS_ERROR);
        }

    }

    /**
     * 查询代办列表
     * @param vo 查询条件
     * @return
     */
    @Override
    public ProcessVo findPendingTaskList(ProcessVo vo) {

        //查询待处理：流程id
        List<Long> processIds = workFlowService.findPendingTaskList(vo.getUserId());
        if (processIds==null || processIds.size()==0){
            return vo;
        }
        //设置流程id
        vo.setProcessIds(processIds);

        //处理分页参数
        handlePage(vo);
        //多条件查询待处理
        return processMapper.findPendingTaskList(vo);
    }

    //查询已处理
    @Override
    public ProcessVo findProcessedTaskList(ProcessVo vo) {
        //处理分页参数
        handlePage(vo);
        return processMapper.findProcessedTaskList(vo) ;
    }

    //查询我发起的
    @Override
    public ProcessVo findInitiateTaskList(ProcessVo vo) {
        //处理分页参数
        handlePage(vo);
        return processMapper.findInitiateTaskList(vo);
    }

    @Override
    public List<ProcessVo> getEmpProcessList(ProcessVo vo) {
        return processMapper.getEmpProcessList(vo);
    }

    private void handlePage(ProcessVo vo) {
        int pageNum = 1;
        int pageSize = 10;
        if (vo.getPageNum()!=null && vo.getPageNum()>0){
            pageNum = vo.getPageNum();
        }
        if (vo.getPageSize()!=null && vo.getPageSize()>0){
            pageSize = vo.getPageSize();
        }
        vo.setOffset((pageNum-1)*pageSize);
    }
}
